from django.conf import settings
from functools import wraps
import requests


def _perform_reload():
    # 先用同步的方式实现，之后看并发情况再决定要不要上Celery
    try:
        reload_url = settings.CAS['SERVER'] + settings.CAS['RELOAD']
        requests.get(reload_url, timeout=2, verify=not settings.DEBUG)
    except Exception as e:
        # TODO take a log
        print('reload CAS resource state failed, %s' % e)


def reload_cas(view_func=None):
    """可以通过函数的形式调用，也可以装饰器方式调用"""
    if view_func is None:  # 函数形式
        _perform_reload()
    else:  # 装饰器形式
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            response = view_func(request, *args, **kwargs)
            if 200 <= response.status_code < 300:
                _perform_reload()
            return response
        return wrapper


def update_user_info(username):
    """更新CAS中的用户信息
    :arg username 用户名或用户名列表
    """
    try:
        if isinstance(username, str):
            username = [username]
        url = settings.CAS['SERVER'] + settings.CAS['UPDATE_USERINFO']
        response = requests.post(url, json={'usernames': username}, timeout=2, verify=not settings.DEBUG)
        response.raise_for_status()
    except Exception as e:
        # TODO take a log
        print('update CAS user info failed, %s' % e)
